
$(function () {
	//页面初始化
	if($("#ship").val()==2){
		$("#shipMethod option[value='2']").attr("selected",true);
	}else if($("#ship").val()==1){
		$("#shipMethod option[value='1']").attr("selected",true);
	}else if($("#ship").val()==3){
		$("#shipMethod option[value='3']").attr("selected",true);
	}

	//兑奖时间
	$('#cashTime_start').daterangepicker({
		"singleDatePicker": true,
		"timePicker": true,
		"timePicker24Hour": true,
		"timePickerSeconds": true,
		"parentEl": "200",
		locale: {
		  format:'YYYY-MM-DD HH:mm:ss',
	      applyLabel: '确认',
	      cancelLabel: '取消',
	      weekLabel: 'W',
	      customRangeLabel: 'Custom Range',
	      daysOfWeek:["日","一","二","三","四","五","六"],
	      monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
		}
	}, function(start, end, label) {
		$('#cashTime_start').val(start.format('YYYY-MM-DD HH:mm:ss'));
		$("#cashTimeS").val(start+"");
	});
	$("#cashTime_start").val("");//清空控件默认时间
	
	$('#cashTime_end').daterangepicker({
		"singleDatePicker": true,
		"timePicker": true,
		"timePicker24Hour": true,
		"timePickerSeconds": true,
		"parentEl": "200",
		locale: {
		  format:'YYYY-MM-DD HH:mm:ss',
	      applyLabel: '确认',
	      cancelLabel: '取消',
	      weekLabel: 'W',
	      customRangeLabel: 'Custom Range',
	      daysOfWeek:["日","一","二","三","四","五","六"],
	      monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
		}
	}, function(start, end, label) {
		$('#cashTime_end').val(start.format('YYYY-MM-DD HH:mm:ss'));
		$("#cashTimeE").val(start+"");
	});
	$('#cashTime_end').val("");//清空控件默认时间
	
	//扫码时间 
	//在非触发方法取得日期值
	//var start = $('#winning_start').daterangepicker().data('daterangepicker').startDate;
	$('#winning_start').daterangepicker({
		"singleDatePicker": true,
		"timePicker": true,
		"timePicker24Hour": true,
		"timePickerSeconds": true,
		"parentEl": "200",
		locale: {
		  format:'YYYY-MM-DD HH:mm:ss',
	      applyLabel: '确认',
	      cancelLabel: '取消',
	      weekLabel: 'W',
	      customRangeLabel: 'Custom Range',
	      daysOfWeek:["日","一","二","三","四","五","六"],
	      monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
		}
	}, function(start, end, label) {
		$('#winning_start').val(start.format('YYYY-MM-DD HH:mm:ss'));
	});
	$('#winning_start').val("");//清空控件默认时间
	
	$('#winning_end').daterangepicker({
		"singleDatePicker": true,
		"timePicker": true,
		"timePicker24Hour": true,
		"timePickerSeconds": true,
		"parentEl": "200",
		locale: {
		  format:'YYYY-MM-DD HH:mm:ss',
	      applyLabel: '确认',
	      cancelLabel: '取消',
	      weekLabel: 'W',
	      customRangeLabel: 'Custom Range',
	      daysOfWeek:["日","一","二","三","四","五","六"],
	      monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
		}
	}, function(start, end, label) {
		$('#winning_end').val(start.format('YYYY-MM-DD HH:mm:ss'));
	});
	$('#winning_end').val("");//清空控件默认时间
	
	//日期时间查询条件不为空的情况下，给控件赋值
	if($("#scanTimeS_hidden").val() != null || $("#scanTimeS_hidden").val() != ""){
		$("#winning_start").val($("#scanTimeS_hidden").val());
	}
	if($("#scanTimeE_hidden").val() != null || $("#scanTimeE_hidden").val() != ""){
		$("#winning_end").val($("#scanTimeE_hidden").val());
	}
	if($("#cashTimeS_hidden").val() != null || $("#cashTimeS_hidden").val() != ""){
		$("#cashTime_start").val($("#cashTimeS_hidden").val());
	}
	if($("#cashTimeE_hidden").val() != null || $("#cashTimeE_hidden").val() != ""){
		$("#cashTime_end").val($("#cashTimeE_hidden").val());
	}


	//点击列表中"详情"按钮
	$("[name='btn_detail_winning']").click(function(){
		
		var winningId = $(this).data("winning-id");
		window.location.href="/activitywinning?id="+winningId;
	});
	//点击列表中"配送"按钮
	$("[name='md_edit_delivery']").click(function(){
		
		var winningId = $(this).data("winning-id");
		window.location.href="/activitywinning?id="+winningId;
	});
    
	// 配送详情
	$('#md_edit_delivery').on('show.bs.modal', function (event) {
	    var _e = $(event.relatedTarget);
	    var winid = _e.data("winning-id");
	    var pzid = _e.data("prizeid");
	    
	    $('#_wind').val(winid);
	    $('#_pzid').val(pzid);
	    var modal = $(this);
	    
	    //打开另外的配送信息时，不要显示上一个配送信息
	    $("#waybillNumber").val("");
	    $("#logisticsCompany").get(0).selectedIndex="";
	    $("#website").val("");
	    $("#consignee").html("");
	    $("#mobile").html("");
	    $("#adress").html("");
	    
	    $.get("/activitywinning/" + winid, function (re) {
	        var winning = re.data;
	        $("#consignee").html(winning.consignee);
	        $("#mobile").html(winning.mobile);
	        $("#adress").html(winning.adress);
	    });
	    
	  //选择承运方，带出承运方官网
		$("[name='logisticsCompanyId']").change(function(){
			var id = $("#logisticsCompany option:selected").val();
			var name="自定义";
			$.get("/logisticscompany/" + name + "/" + id, function (re) {
		        var logistics = re.data;
		        $("#website").val(logistics.website);
		    });
		});
		
	});
	
//	 var _e = $(event.relatedTarget);
//	    var winid = _e.data("winning-id");
//	    var modal = $(this);
	//保存承运方信息
	$("[name='btn_save_edit_delivery']").click(function(){
		
		
		
		var form = window.form_edit_delivery;
		if($("#consignee").html()=="" || $("#mobile").html() == "" || $("#adress").html() == ""){
			bootbox.balert("收件人信息不完整，无法配送!");
			return false;
		}
		
		var logisticsCompanyId = form.logisticsCompanyId.value;//承运方id
		var waybillNumber = form.waybillNumber.value;//运单号
		var activityWinningId = $('#_wind').val()//兑奖记录id
		if(logisticsCompanyId =="" ||logisticsCompanyId==null){
			bootbox.balert("请选择承运方!");
			return false;
		}
		if(waybillNumber =="" ||waybillNumber==null){
			bootbox.balert("请填写运单号!");
			return false;
		}
		var pzid =  $('#_pzid').val();
		var info = {logisticsCompanyId: logisticsCompanyId, waybillNumber: waybillNumber,activityWinningId:activityWinningId,pzid:pzid };
        $.postJsonBody("/deliverInfo", info, function (re) {
            // tipper.success("已保存，请刷新页面");
        	window.location.href=window.location.href; 
        	window.location.reload; 
        })
	});
   

	//加载异步数据 :承运方列表 logisticsCompanyId
	 $.get("/logisticscompany?state=1", function (re) {
	        var logisticsList = re.data;
	        var form = window.form_edit_delivery;
	        var logisOptions = "";
	        for (var i in logisticsList) {
	            var logistics = logisticsList[i];
	            logisOptions += "<option value='" + logistics.id + "'>" + logistics.name + "</option>";
	        }
	        if(window.form_edit_delivery != null){
	        	$(window.form_edit_delivery.logisticsCompanyId).append(logisOptions);
	        }
	    });


	 
	//取消兑奖详情 
	$("[name='btn_cancel_detail_winning']").click(function(){
		window.location.href="/activitywinning";
	});
	
	//查询条件重置
	$("#search_reset").click(function(){
		$("input").not($("#activityId_hidden")).val("");
	    $("select").val("");
	});


	//数据导出
	$("[name='btn_export']").click(function () {
		var activityId = $("[name='activityId']").val();
	    var qrcodeNum = $("[name='qrcodeNum']").val();
	    var qrcodeName = $("[name='qrcodeName']").val();
	    var productName = $("[name='productName']").val();
	    var prizeName = $("[name='prizeName']").val();
	    var csshMobile = $("[name='csshMobile']").val();
	    var scanTimeS = $("[name='scanTimeS']").val();//扫码时间
	    var scanTimeE = $("[name='scanTimeE']").val();
	    var cashTimeS = $("[name='cashTimeS']").val();//兑奖时间
	    var cashTimeE = $("[name='cashTimeE']").val();
	    var shipMethod = $("[name='shipMethod']").val();
	    var redEnvelope= $("#redEnvelope").val();
	    
	    //有数据时才能导出
	    if($("#resultTotal_hidden").val() != 0){
	    	bootbox.bconfirm("确定是否导出？", function (re) {
	            if (re) {
	            	 var url="/activitywinning/export?activityId="+activityId + "&qrcodeNum="+qrcodeNum+"&qrcodeName="+qrcodeName+"&productName="+productName
	            	 +"&prizeName="+prizeName+"&csshMobile="+csshMobile+"&scanTimeS="+scanTimeS+"&scanTimeE="+scanTimeE+
	            	 "&cashTimeS="+cashTimeS+"&cashTimeE="+cashTimeE+"&shipMethod="+shipMethod +"&redEnvelope=" +redEnvelope;
	                 window.open(url);
	            }
	        });
	    }else{
	    	bootbox.balert("没有数据，无法导出!");
	    }
	});

    $("#btn_tatistical").click(function () {
        var activityId = $("[name='activityId']").val();

        bootbox.bconfirm("确定是否导出统计报表数据？", function (re) {
            if (re) {
                var url="/activitywinning/tatisticalForm?activityId="+activityId ;
                window.open(url);
            }
        });

    });
	
	
});

/**
 * 点击发送
 */
$("[name='send_evn']").click(function () {
    var winningId = $(this).data("winningid"), prizeId = $(this).data("prizeid")
    bootbox.bconfirm("是否确定重新发送？", function (re) {
        if (re) {
            jQuery.ajax({
                type:'post',
                url:'/sendEnvelope',
                data:{'winningId': winningId, 'prizeId':prizeId},
                dataType:'json',
                cache:false,
                success:function(data){
                    tipper.success("操作成功！");
                    window.location.href=window.location.href;
                    window.location.reload;
                },
                error:function(){
                    tipper.danger("操作失败！请刷新后重新操作");
                }
            });

        }
    });
});

/**
 * 红包补发数据
 */
$("#btn_send_evn_false").click(function () {

	var activityId = $("#activityId_hidden").val();
    bootbox.bconfirm("确定是否导出红包补发数据？", function (re) {
        if (re) {
            var url="/getSendEvnFalse?activityId=" + activityId;
            window.open(url);
        }
    });
});

//===================以下为公共方法============================

/**   
*转换long值为日期字符串   
* @param l long值   
* @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss   
* @return 符合要求的日期字符串   
*/    

function getFormatDateByLong(l, pattern) {  
    return getFormatDate(new Date(l), pattern);  
}
/**   
 *转换日期对象为日期字符串   
 * @param l long值   
 * @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss   
 * @return 符合要求的日期字符串   
 */    
 function getFormatDate(date, pattern) {  
     if (date == undefined) {  
         date = new Date();  
     }  
     if (pattern == undefined) {  
         pattern = "yyyy-MM-dd hh:mm:ss";  
     }  
     return date.format(pattern);  
 }
//扩展Date的format方法   
 Date.prototype.format = function (format) {  
     var o = {  
         "M+": this.getMonth() + 1,  
         "d+": this.getDate(),  
         "h+": this.getHours(),  
         "m+": this.getMinutes(),  
         "s+": this.getSeconds(),  
         "q+": Math.floor((this.getMonth() + 3) / 3),  
         "S": this.getMilliseconds()  
     }  
     if (/(y+)/.test(format)) {  
         format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
     }  
     for (var k in o) {  
         if (new RegExp("(" + k + ")").test(format)) {  
             format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));  
         }  
     }  
     return format;  
 } 